﻿#include "widget.h"
#include "ui_widget.h"
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QString>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QStringList SerialName;
    serilaPort = new QSerialPort;

    //关联收发
    connect( serilaPort,SIGNAL(readyRead()),this,SLOT(serilaPortReadyRead_Slot()) );

    //检测电脑端口
    foreach (const QSerialPortInfo &info , QSerialPortInfo::availablePorts()) {
        SerialName << info.portName();
    }
    //显示端口到SeialCb
    ui->SeialCb->addItems(SerialName);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::serilaPortReadyRead_Slot()
{
    QString buf;
    buf = QString( serilaPort->readAll() );
    ui->ReciveEdit->appendPlainText(buf);
}

void Widget::on_btn_open_clicked()
{
    QSerialPort::BaudRate baudRate;
    QSerialPort::DataBits dataBits;
    QSerialPort::StopBits stopBits;
    QSerialPort::Parity checkBits;//校验位

    if( ui->baudrateCb->currentText() == "4800" ){
        baudRate = QSerialPort::Baud4800;
    }else if( ui->baudrateCb->currentText() == "9600" ){
        baudRate = QSerialPort::Baud9600;
    }else if( ui->baudrateCb->currentText() == "115200" ){
        baudRate = QSerialPort::Baud115200;
    }

    if( ui->DataCb->currentText() == "5")dataBits = QSerialPort::Data5;
    else if( ui->DataCb->currentText() == "6")dataBits = QSerialPort::Data6;
    else if( ui->DataCb->currentText() == "7")dataBits = QSerialPort::Data7;
    else if( ui->DataCb->currentText() == "8")dataBits = QSerialPort::Data8;


    if( ui->StopCb->currentText() == "1")stopBits = QSerialPort::OneStop;
    else if( ui->StopCb->currentText() == "1.5")stopBits = QSerialPort::OneAndHalfStop;
    else if( ui->StopCb->currentText() == "2")stopBits = QSerialPort::TwoStop;


    if( ui->CheckCb->currentText() == "None")checkBits = QSerialPort::NoParity;

    serilaPort->setPortName(ui->SeialCb->currentText() );
    serilaPort->setBaudRate( baudRate );
    serilaPort->setDataBits( dataBits );
    serilaPort->setStopBits( stopBits );
    serilaPort->setParity( checkBits );

    if(serilaPort->open( QIODevice::ReadWrite ) == true){
        QMessageBox::information( this,"提示","成功" );
    }else{
        QMessageBox::information( this,"提示","失败" );
    }

}

void Widget::on_btn_close_clicked()
{
    serilaPort->close();
}

void Widget::on_btn_send_clicked()
{
    serilaPort->write( ui->SendtEdit_2->toPlainText().toLocal8Bit().data() );
}

void Widget::on_btn_clear_clicked()
{
    ui->ReciveEdit->clear();
}
